package cn.com.dycc.topic_activity.service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.party_org.organize.dao.OrganizeDao;

import cn.com.dycc.party_org.organize.param.PartyInfoParam;
import cn.com.dycc.party_org.organize.service.OrganizeService;
import cn.com.dycc.study_manage.integral.dao.Pb_Integral_LogDao;
import cn.com.dycc.study_manage.integral.dao.Pb_Integral_RuleDao;
import cn.com.dycc.study_manage.integral.entity.Pb_Integral_Log;
import cn.com.dycc.study_manage.integral.entity.Pb_Integral_Rule;
import cn.com.dycc.study_manage.integral.param.Pb_Integral_RuleParam;
import cn.com.dycc.sys_manage.deptsysmanagement.dao.DeptDao;
import cn.com.dycc.topic_activity.dao.Pb_Activity_ResultDao;
import cn.com.dycc.topic_activity.dao.Pb_Special_ActivityDao;
import cn.com.dycc.topic_activity.entity.Pb_Activity_Result;
import cn.com.dycc.topic_activity.entity.Pb_Special_Activity;
import cn.com.dycc.topic_activity.param.Pb_Activity_ResultParam;
import cn.com.dycc.topic_activity.param.Pb_Special_ActivityParam;
import cn.com.dycc.util.AttachUtil;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.JsonObjectResult;
import cn.com.dycc.util.PageObjectUtil;
import cn.com.dycc.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("pb_Activity_ResultService")
@Transactional
public class Pb_Activity_ResultServiceImpl implements Pb_Activity_ResultService{

	@Resource
	private Pb_Activity_ResultDao pb_Activity_ResultDao;
	@Resource
	private AttachDao attachDao;
	@Resource
	private Pb_Integral_RuleDao pb_Integral_RuleDao;
	@Resource
	private Pb_Integral_LogDao pb_Integral_LogDao;
	@Resource
	private Pb_Special_ActivityDao pb_Special_ActivityDao;
	
	@Resource
	private DeptDao deptDao;
	
	@Resource
	private OrganizeDao organizeDao;
	
	@Resource
	private OrganizeService organizeService;
	
	
	
	@SystemServiceLog(description=Constants.ACTIVITY_RESULT_ADD)
	public int addPb_Activity_Result(Pb_Activity_ResultParam param, HttpServletRequest request)
			throws Pb_Activity_ResultNotFoundException {
		checkParam(param);
		HttpSession session=request.getSession();
		String user_id=(String)session.getAttribute("id");
		String report_date=DateUtil.getNowTimestamp().toString();
		String org_id=(String)session.getAttribute("org_id");
		String dept_id=(String)session.getAttribute("dept_id");
		String username=(String)session.getAttribute("username");
		if(dept_id==null||dept_id.trim().isEmpty()){
			throw new Pb_Activity_ResultNotFoundException("该用户不是党员不能汇报");
		}
		StringBuilder builder=new StringBuilder();
		if(param.getResult_title()==null||param.getResult_title().trim().isEmpty()){
			builder.append("汇报标题不能为空;");
		}
		if(param.getActivity_id()==null||param.getActivity_id().trim().isEmpty()){
			builder.append("请选择汇报的专题活动;");
		}
		if(!"".equals(builder.toString())){
			throw new Pb_Activity_ResultNotFoundException(builder.toString());
		}
		//20180802 start
		Pb_Special_ActivityParam activity_param=new Pb_Special_ActivityParam();
		activity_param.setActivity_id(param.getActivity_id());
		activity_param.setIssue_flag("1");
		activity_param.setStart(0);
		activity_param.setEnd(1);
		List<Pb_Special_Activity> activities=pb_Special_ActivityDao.findPb_Special_ActivityByParam(activity_param);
		if(activities.size()<0){
			throw new Pb_Activity_ResultNotFoundException("要汇报的专题活动不存在或未发表");
		}
		Pb_Special_Activity activity=activities.get(0);
		Date enter_date_b=activity.getEnter_date_b();
		Date enter_date_e=activity.getEnter_date_e();
		long now=System.currentTimeMillis();
		long begin=enter_date_b.getTime();
		long end=enter_date_e.getTime()+24*60*60*1000;
		if(now-begin<0){
			throw new Pb_Activity_ResultNotFoundException("专题活动报名未开始,不能汇报");
		}
		if(now-end<0){
			throw new Pb_Activity_ResultNotFoundException("专题活动报名未结束,不能汇报");
		}
		//20180802 end
		param.setDept_id(dept_id);
		param.setUser_id(user_id);
		param.setReport_date(report_date);
		param.setState("Y");
		param.setOrg_id(org_id);
		List<Pb_Activity_Result> lists = getServiceList(param);
		Pb_Activity_Result entity=lists.get(0);
		int d = pb_Activity_ResultDao.savePb_Activity_Result(entity);
		if(d>0){
			if(param.getAttachs()!=null&&!param.getAttachs().trim().isEmpty()){
				saveT_Attach(param.getAttachs(),entity,AttachUtil.activity_result_attach_type);
			}
			Pb_Integral_RuleParam param1=new Pb_Integral_RuleParam();
			param1.setStart(0);
			param1.setEnd(1);
			List<Pb_Integral_Rule> list2=pb_Integral_RuleDao.findPb_Integral_RuleByParam(param1);
			if(list2.size()>0){
				Pb_Integral_Rule rule=list2.get(0);
				
				Pb_Integral_Log entity1=new Pb_Integral_Log();
				entity1.setIntegral_val(rule.getActivity_reply_val());
				entity1.setLog_flag("11");
				entity1.setUser_id(entity.getUser_id());
				entity1.setDept_id(entity.getDept_id());
				entity1.setState("Y");
				entity1.setOrg_id(entity.getOrg_id());
				entity1.setCreate_date(DateUtil.getNowTimestamp());
				entity1.setInfo_id(entity.getResult_id());
				
				entity1.setLog_des(username+"于"+DateUtil.getNowDate(DateUtil.TIME_FMT)+"操作【"+activity.getActivity_name()+"】活动反馈,获取积分"+rule.getActivity_reply_val()+"X分");
				pb_Integral_LogDao.savePb_Integral_Log(entity1);
			}
			
		}
		
		return d;
		
	}

	

	

	
	
	
	
	/**
	 * 校验 @param param @return @throws
	 */
	public void checkParam(Pb_Activity_ResultParam param) {
		if (param == null) {
			throw new Pb_Activity_ResultNotFoundException("未登录或超时,请重新登录");
		}
		
		
	}

	public List<Pb_Activity_Result> getServiceList(Pb_Activity_ResultParam param) {
		Pb_Activity_Result entity = new Pb_Activity_Result();

		entity.setResult_id(param.getResult_id());
		entity.setResult_title(param.getResult_title());
		entity.setActivity_id(param.getActivity_id());
		entity.setUser_id(param.getUser_id());
		entity.setDept_id(param.getDept_id());
		entity.setReport_des(param.getReport_des());
		if(param.getReport_date()!=null&&!param.getReport_date().trim().isEmpty()){
			entity.setReport_date(Timestamp.valueOf(param.getReport_date()));

		}
		entity.setState(param.getState());
		entity.setOrg_id(param.getOrg_id());
				
		List<Pb_Activity_Result> lists = new ArrayList<Pb_Activity_Result>();
		lists.add(entity);
		return lists;
	}
	
	/**
	 * 将临时目录下的文件移到正式目录
	 */
	private void saveT_Attach(String attachInfos,Pb_Activity_Result entity,String attach_type){
		List<Attach> listAttach=new ArrayList<Attach>();
		
		if(attachInfos!=null&&!attachInfos.trim().isEmpty()){
			
			String str=attachInfos.trim();
			
			JSONArray json=JSONArray.fromObject(str);
			
			for(int i=0;i<json.size();i++){
				
				Object check=json.get(i);
				
				
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象			
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				
				Attach attach=new Attach();
				attach.setMessage_no(entity.getResult_id());
				attach.setAttach_type(Integer.valueOf(attach_type));
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(entity.getOrg_id());
				attach.setOpt_user_id(entity.getUser_id());
				
				attach.setCreate_date(DateUtil.getNowTimestamp());
				
				listAttach.add(attach);			
			}
		}
		
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"topic_activity");
		
		if(newListAttach!=null){
			for(Attach attach:newListAttach){
				
				attachDao.insertAttach(attach);
			}
						
		}
		
	}








	@SystemServiceLog(description=Constants.ACTIVITY_RESULT_DELETE)
	public int deletePb_Activity_Result(String[] attrStrs, HttpServletRequest request)
			throws Pb_Activity_ResultNotFoundException {
		if (attrStrs == null) {
			throw new Pb_Activity_ResultNotFoundException("请选择要删除的专题活动成果汇报信息");
		}
		int d = pb_Activity_ResultDao.deletePb_Activity_Result(attrStrs);
		return d;
	}




	public JsonObjectResult findPb_Activity_ResultByParam(Pb_Activity_ResultParam param, HttpServletRequest request)
			throws Pb_Activity_ResultNotFoundException {
		List<Pb_Activity_Result> lists = new ArrayList<Pb_Activity_Result>();
		
		checkParam(param);
		//20180802 start
		HttpSession session=request.getSession();
		String dept_id=(String)session.getAttribute("dept_id");
		if(dept_id==null){
			throw new Pb_Special_ActivityNotFoundException("该用户不是党员");
		}
		if(param.getUser_id()==null&&"1".equals(param.getLeader_flag())){
			PartyInfoParam partyInfoParam=new PartyInfoParam(); 
			String party_dept=dept_id;
			List<String> dept_party_list=organizeService.findTreeByPidLine(request, partyInfoParam, party_dept);
			if(!dept_party_list.isEmpty()){
				param.setDept_party_list(dept_party_list);
			}else {
				throw new Pb_Special_ActivityNotFoundException("该部门及其子部门下无相应的党支部信息");
			}
			System.out.println("dept_party_list:"+dept_party_list);
		}
		//20180802 end
		param = realParam(param, request);
		String count = pb_Activity_ResultDao.getPb_Activity_ResultCountByParam(param);
		
		if ("0".equals(count)) {			
			return new JsonObjectResult(lists);
		}
		param = (Pb_Activity_ResultParam) PageObjectUtil.getSqlPageObject(count, param);
		lists = pb_Activity_ResultDao.findPb_Activity_ResultByParam(param);
		
		
		return new JsonObjectResult(count,lists);
	}
	
	/**
	 * 实际参数
	 * 
	 * @param param
	 * @param request
	 * @return
	 */
	public Pb_Activity_ResultParam realParam(Pb_Activity_ResultParam param, HttpServletRequest request) {
		if(param.getResult_title()!=null&&!param.getResult_title().trim().isEmpty()){
			param.setResult_title(StringUtil.format_mh_str(param.getResult_title()));
		}
		if(param.getReport_des()!=null&&!param.getReport_des().trim().isEmpty()){
			param.setReport_des(StringUtil.format_mh_str(param.getReport_des()));
		}
		if(param.getActivity_name()!=null&&!param.getActivity_name().trim().isEmpty()){
			param.setActivity_name(StringUtil.format_mh_str(param.getActivity_name()));
		}
		if(param.getOrder()==null||param.getOrder().isEmpty()||"1".equals(param.getOrder())){
			param.setOrder("p.report_date desc");
		}else if("2".equals(param.getOrder())){
			param.setOrder("p.report_date asc");
			
		}else{
			param.setOrder(null);//手动防止SQL注入
		}
		return param;
	}

}
